package cn.web;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;


public class GlobalFilter implements Filter {

	private ServletContext context;
	
	public final static String REQUEST_URI = "request_uri";	//{/index}
	

	private List<String> ignoreURIs = new ArrayList<String>();
	private List<String> ignoreExts = new ArrayList<String>();
	
	
	public void init(FilterConfig cfg) throws ServletException {
		this.context = cfg.getServletContext();
		
		String ignores = cfg.getInitParameter("ignore");
		
		if(ignores != null)
		for(String ig : StringUtils.split(ignores, ','))
			ignoreURIs.add(ig.trim());
		
		ignores = cfg.getInitParameter("ignoreExts");
		if(ignores != null)
		for(String ig : StringUtils.split(ignores, ','))
			ignoreExts.add('.'+ig.trim());
	}
	
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		RequestContext rc = RequestContext.begin(this.context, request, response);
		String req_uri = rc.uri();

		try{
			for(String ignoreURI : ignoreURIs){
				ignoreURI=request.getContextPath()+ignoreURI;
				if(req_uri.startsWith(ignoreURI)){
					chain.doFilter(rc.request(), rc.response());
					return ;
				}
			}
			for(String ignoreExt : ignoreExts){
				if(req_uri.endsWith(ignoreExt)){
					chain.doFilter(rc.request(), rc.response());
					return ;
				}
			}
		} catch (SecurityException e){
			String login_page = e.getMessage() + "?goto_page=" + URLEncoder.encode(req_uri,"utf-8");
			rc.sendRedirect(login_page);
		} finally {
			if(rc!=null) rc.end();
		}
	}
	
	public void destroy() {
	}
}
